﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MCServerHelper.Properties;
using System.IO;
using System.Timers;
using System.Net;

namespace MCServerHelper.Services
{
    public class BackupService : IMinecraftService
    {
        private TimeSpan _backupTime;
        private DateTime _lastBackup = DateTime.Now;
        private bool _isBackingUp = false;
        private MinecraftServer _server;
        private Timer _timer = null;
        private WebClient _webClient = null;
        private string _tempDownloadPath = string.Empty;
        private Action _downloadCompletedAction = null;

        public void Initialize(MinecraftServer server)
        {
            _webClient = new WebClient();
            _webClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(webClient_DownloadFileCompleted);

            _server = server;
            _backupTime = Settings.Default.BackupTime;
            InitializeTimer();
        }

        public void ProcessOutput(string output)
        {
            if (Settings.Default.AllowServerCommands)
            {
                if (output.Contains("FORCEBACKUP"))
                {
                    StartBackupProcess();
                }
            }
        }

        private void InitializeTimer()
        {
            // Timer fires every minute
            _timer = new Timer(60000);
            _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
            _timer.Enabled = true;

        }

        private void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            // If we haven't done a backup today, and we've passed the backup time, go for it
            if (_lastBackup.Date < DateTime.Now.Date)
            {
                if (DateTime.Now.Subtract(DateTime.Now.Date) > _backupTime)
                {
                    StartBackupProcess();
                }
            }
        }

        private void StartBackupProcess()
        {
            // Time to backup and reboot!
            _timer.Enabled = false;
            _isBackingUp = true;
            _server.BeginStop();
        }

        public void Dispose()
        {
        }

        private void Backup()
        {
            DirectoryInfo backupSource = new DirectoryInfo(Settings.Default.BackupSource);
            DirectoryInfo backupRoot = new DirectoryInfo(Settings.Default.BackupDestination);

            // Create a new folder to house the backup
            string backupFolderName = DateTime.Now.ToString("yyyy-MM-dd hh.mm.ss");
            DirectoryInfo backupDestination = backupRoot.CreateSubdirectory(backupFolderName);
            CopyRecursively(backupSource, backupDestination);
            _lastBackup = DateTime.Now;
        }

        private void CopyRecursively(DirectoryInfo source, DirectoryInfo destination)
        {
            foreach (FileInfo file in source.GetFiles())
            {
                file.CopyTo(destination.FullName + Path.DirectorySeparatorChar + file.Name, true);
            }

            foreach (DirectoryInfo subdirsource in source.GetDirectories())
            {
                DirectoryInfo subdirdest = destination.CreateSubdirectory(subdirsource.Name);
                CopyRecursively(subdirsource, subdirdest);
            }
        }

        public void ServerStopped()
        {
            if (_isBackingUp)
            {
                Backup();

                if (Settings.Default.AutoUpdateServer)
                {
                    BeginUpdate(() =>
                        {
                            _server.Start();
                        });
                }
                else
                {
                    _server.Start();
                }
            }
        }

        private void BeginUpdate(Action completed)
        {
            _downloadCompletedAction = completed;
            LogUtility.LogMessage("Downloading for Minecraft Server...");
            _tempDownloadPath = string.Format("{0}{1}{2}", Path.GetTempPath(), Path.DirectorySeparatorChar, Path.GetRandomFileName());
            _webClient.DownloadFileAsync(new Uri(Settings.Default.ServerUpdatePath), _tempDownloadPath);
        }

        private void webClient_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            Exception error = null;
            if(e.Error != null)
            {
                error = e.Error;
            }
            else if(e.Cancelled)
            {
                error = new Exception("Download has been cancelled.");
            }

            if (error == null && File.Exists(_tempDownloadPath))
            {
                try
                {
                    File.Copy(_tempDownloadPath, Settings.Default.MinecraftServerPath, true);
                }
                catch (Exception ex)
                {
                    error = ex;
                }
                finally
                {
                    try
                    {
                        File.Delete(_tempDownloadPath);
                    }
                    catch (Exception innerEx)
                    {
                        error = innerEx;
                    }

                    _tempDownloadPath = string.Empty;
                }
            }

            if (error != null)
            {
                LogUtility.LogException(error);
            }

            _downloadCompletedAction();
            _downloadCompletedAction = null;
            LogUtility.LogMessage("Download completed.");
        }

        public void ServerStarted()
        {
        }

        public void PlayerConnected(string name, string ip)
        {
        }
    }
}
